Constants and variables are the most basic language elements (like words in English or characters in Chinese). Learning Python starts here.
Constants
Constants are predefined objects with fixed values in Python, such as True, False, and None:
True/False: Boolean values representing logical truth/falsity.
None: Represents an empty object (missing value). Constants cannot be modified during execution.
Some built-in or third-party modules also predefine constants. For example, the math module defines pi (π). Import the module first with import:
>>> import math
>>> math.pi
3.141592653589793
Variables: Declaration, Assignment, and Deletion
In Python, variables do not need explicit declaration—declaration and assignment are done in one step: assigning a value to a variable creates it.
Use the assignment operator = to assign values. For example:
>>> a = 1 # Create variable a and assign 1
>>> a # Check the value of a
1
>>> print(a) # Output the value of a
1
Data Types of Variables
Each variable has a data type. Common types include Boolean, numeric, string, list, tuple, etc. (Table 2-1). This chapter also covers structured types: NumPy arrays, pandas Series, and pandas DataFrame.
Table 2-1 Common Python Data Types
| Type Name | Type Character | Description | Example |
|---|---|---|---|
| Boolean | bool | Values: True or False | >>> a=True; b=False |
| Integer | int | Integers (no size limit) | >>> a=1; b=10000000 |
| Float | float | Decimal numbers (supports scientific notation) | >>> a=1.2; b=1.2e3 |
| String | str | Immutable sequence of characters | >>> a='A'; b='A' |
| List | list | Mutable, ordered, allows duplicates | >>> a=[1, 'A', 3.14, []] |
| Tuple | tuple | Immutable (similar to lists) | >>> a=(1, 'A', 3.14, ()) |
| Dictionary | dict | Unordered key-value pairs (unique keys) | >>> a={1:'A', 2:'B'} |
| Set | set | Unordered, mutable, no duplicates | >>> a={1, 3.14, 'name'} |
| None | NoneType | Represents an empty object | >>> a=None |